<template>
    <view class="calendar">
        <block v-if="!$u.test.isEmpty(this.list)">
        <view class="content-tabs">
            <u-tabs
                    :activeStyle="{
                        color: themeColor,
                        fontSize: '28rpx',
                        padding:'0 9rpx',
                        transform: 'scale(1.05)'
                    }"
                    :itemStyle="{
                         height: '40px',
                         alignItems:'flex-start',
                         padding:'0 30rpx',
                    }"
                    :inactiveStyle="{
                        color: '#646566',
                        fontSize: '28rpx',
                        padding:'0 9rpx',
                        transform: 'scale(1)'
                    }"
                    :list="tabs"
                    lineWidth="35"
                    lineHeight="2"
                    :current="current"
                    :lineColor="themeColor"
                    @change="changeTab"
            ></u-tabs>
        </view>
        <view class="calendar-content">
            <view class="weekdays pd20">
                <view class="weekday" :style="day=='日'||day=='六'?'color:'+themeColor:''" v-for="(day, index) in weekdays" :key="index">
                    {{ day }}
                </view>
            </view>
            <view class="days pd20">
                <view
                        class="day wlkflex justify-center wrap"
                        v-for="(date, index) in monthDates"
                        :key="index"
                        :style="{backgroundColor:selectedDate.date === date.date && date.date?themeColor:''}"
                        :class="{ 'selected': selectedDate.date === date.date,'disabled': !isCurrentMonth(date) }"
                        @tap="isCurrentMonth(date) && selectDate(date)"
                >
                    <view class="wlkflex justify-center wrap">
                        <view class="day-info-title">
                            {{ date.day?date.day:'' }}
                        </view>
                        <view class="wd100 minprice"
                              :style="{color:selectedDate.date != date.date && date.date?'#FF5904':''}">
                            {{isCurrentMonth(date)?'￥'+date.minprice:''}}
                        </view>
                       <!-- <view class="wd100 stock" :style="selectedDate != date?{
                            color:'#999'
                        }:''">{{date.stock==-1?'':isCurrentMonth(date)?'余'+date.stock:''}}</view>-->
                    </view>
                </view>
            </view>
        </view>
        </block>
        <block v-else>
            <view class="not-data">
                <u-empty
                        icon="https://cdn.uviewui.com/uview/empty/data.png"
                        text="此套餐暂无报价"
                >
                </u-empty>
            </view>
        </block>
    </view>
</template>

<script>
    import { mapGetters } from 'vuex';
    export default {
		name:"wlk-calendar",
		data() {
			return {
                weekdays: ['日', '一', '二', '三', '四', '五', '六'],
                currentYear:'',//价格数据的第一个年份
                currentMonth: '',//价格数据的第一个月份
                currentDay: new Date().getDate(),
                nowDate:{
                    year: new Date().getFullYear(),
                    month: (new Date().getMonth() + 1).toString().padStart(2, '0'),
                    day: new Date().getDate(),
                },//当前年月日
                priceDate:'',//选中的年月日
                selectedDate: '', // 选中的日期对象
                currentDate: {
                    year: new Date().getFullYear(),
                    month: new Date().getMonth() + 1,
                }, // 当前选择的年份和月份
                current:0,
                monthDates:{}//当前月的价格数据


            }
		},
        //属性
        props: {
            tabs: {
                type: Array,
                default: () => []
            },
            list: {
                type: Object,
                default: () => {}
            },
            mode:{
                type:String,
                default:''
            },
            priceIndex:{
                type:String,
                default:''
            },
        },
        watch: {
            list(val) {
                this.current = 0;
                this.setFirstDate();
                this.visibleDates();
                this.selectDate();

            },
            priceIndex(val){
                // this.priceDate = val;
            }
        },
        created:function(){
            this.priceDate = this.priceIndex;
            //判断线路详情页选中的日期是在日期tabs中的第几个
            const targetYearMonth = this.priceDate.substring(0, 7).replace('-', '');
            const targetKey = this.tabs.findIndex(item => item.date.replace('-', '') === targetYearMonth);
            if(targetKey>-1){
                this.current = targetKey;
            }
            this.setFirstDate();
            this.visibleDates();
        },
        computed:{

            // 获取当前月份的天数
            totalDays() {
                return new Date(this.currentYear, this.currentMonth, 0).getDate();
            },
            // 获取当前月份的第一天是星期几
            firstDay() {
                return new Date(`${this.currentYear}-${this.currentMonth}-01`).getDay();
            },
            ...mapGetters(['userInfo','themeColor'])
        },
        methods: {
            //设置价格数据的第一个月
            setFirstDate(){
                if(this.tabs.length>0){
                    var firstKey = this.tabs[this.current].date;
                    this.currentYear = firstKey.substr(0, 4); // 提取年份
                    this.currentMonth = firstKey.substr(5, 2); // 提取月份
                }
            },
            // 获取当前月份显示的日期列表
            visibleDates() {
                var that = this;
                if(!uni.$u.test.isEmpty(this.list)){
                    const prevMonthDays = this.firstDay; // 上个月显示的天数
                    this.currentMonth === 12 ? this.currentYear + 1 : this.currentYear; // 下个月的年份
                    const dates = [];

                    // // 添加上个月的日期
                    for (let i = prevMonthDays; i > 0; i--) {
                        let obj = new Object();
                        dates.push(obj);
                    }
                    // 添加当前月的日期
                    for (let i = 1; i <= this.totalDays; i++) {
                        let obj = new Object();
                        obj.year = this.currentYear;
                        obj.month = this.currentMonth;
                        obj.day = i;
                        let key= obj.year+'-'+obj.month;
                        let where= key+'-'+obj.day.toString().padStart(2, '0');
                        obj.date = where;
                        const filteredArr = that.list[key].filter(temp => temp.date == where)
                        if(filteredArr.length>0){
                            obj.minprice = filteredArr[0].minprice;
                            obj.stock = filteredArr[0].stock;
                            obj.id = filteredArr[0].id;
                            obj.suitid = filteredArr[0].suitid;
                            obj.lineid = filteredArr[0].lineid;
                            obj.price = filteredArr[0].price;
                            obj.elderprice = filteredArr[0].elderprice;
                            obj.childprice = filteredArr[0].childprice;
                            obj.bxinfo = filteredArr[0].bxinfo;
                            obj.roomblance = filteredArr[0].roomblance;
                            obj.roomcount = filteredArr[0].roomcount;
                        }else{
                            obj.minprice = 0;
                            obj.stock = 0;
                        }
                        obj.timestamp = this.getTimestamp(obj.year,obj.month,obj.day)
                        dates.push(obj);
                        //第一次加载时，直接返回默认选中的价格日期数据
                        if(where == this.priceDate && (obj.stock==-1 || obj.stock>0)){
                            that.selectDate(obj);
                        }
                    }
                    this.monthDates = dates;
                }

            },
            changeTab(item){
                this.current = item.index
                const year = item.date.substr(0, 4); // 提取年份
                const month = item.date.substr(5, 2); // 提取月份
                this.currentMonth = month;
                this.currentYear = year;
                this.visibleDates();
            },

            // 判断日期是否大于等于当天以及库存
            isCurrentMonth(date) {
                let nowTimestamp  =  this.getTimestamp(this.nowDate.year,this.nowDate.month,this.nowDate.day);
                return (
                    date.timestamp >= nowTimestamp && (date.stock==-1 || date.stock>0 || date.minprice>0)
                );
            },
            // 选中日期
            selectDate(date={}) {
                if(this.selectedDate.date!=date.date){
                    this.selectedDate = date;
                    this.priceDate = date.date;
                    this.$emit('selectedDate',date);//传递选中的价格日期
                }
            },
            getTimestamp(year, month, day) {
                const date = new Date(year, month - 1, day); // 月份需要减去1，因为月份在 Date 对象中是从 0 开始的
                const timestamp = Math.floor(date.getTime() / 1000); // 获取毫秒级时间戳并将其转换为秒级
                return timestamp;
            }
        },
	}
</script>

<style lang="scss">

    .calendar {
        .content-tabs{
            background-color: #FFFFFF;
            padding-top: 23rpx;
            width: 100%;
            height: 49px;
        }
        .calendar-content{
            .weekdays {
                border-bottom: 1px solid #F3F3F3;
                display: flex;
                justify-content: space-between;
                margin-bottom: 20rpx;
                background-color: #F9F9F9;
                overflow: visible;
                .weekday {
                    width: calc(100% / 7);
                    text-align: center;
                    font-size: $font-lt
                }
            }
            .days {
                display: grid;
                grid-template-columns: repeat(7, 1fr);
                grid-gap: 0;
                font-size: $font-base;
            }

            .day {
                text-align: center;
                /*border: 1px solid #ccc;*/
                cursor: pointer;
                font-size: $font-sm;
                height: 100rpx;
                .day-info-title{
                    font-size: $font-base;
                }
                .minprice{
                    min-height: 34rpx;
                }
                .stock{
                    min-height: 32rpx;
                }
            }

            .selected {
                color: #FFFFFF;
                border-radius: 4px;
            }

            .day.disabled {
                color: #ccc;
                cursor: default;
                pointer-events: none;

            }
        }

    }

</style>